<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浙江工商大学食堂点单管理系统 - 购物车</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <style>
        /* 重置盒模型 */
        *, *::before, *::after {
            box-sizing: border-box;
        }
        .header {
            width: 100%;
            background-color: #fff;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;
        }
        .header img {
            height: 40px;
        }
        .cart-items {
            display: flex;
            flex-direction: column;
            gap: 20px;
            margin-top: 100px; /* 给顶部的搜索栏留出空间 */
            padding: 20px;
            width: 100%;
        }
        .cart-item {
            width: 100%;
            background-color: #ffffff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .cart-item img {
            width: 100px;
            height: auto;
            border-radius: 8px;
        }
        .cart-item-details {
            flex-grow: 1;
            padding: 0 20px;
        }
        .cart-item-details h3 {
            font-size: 18px;
            margin: 10px 0;
        }
        .cart-item-details p {
            margin: 5px 0;
        }
        .cart-item-actions {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .cart-item-actions button {
            background-color: #007bff;
            border: none;
            color: white;
            padding: 10px;
            border-radius: 4px;
            cursor: pointer;
            width: 100px;
        }
        .footer-buttons {
            width: 100%; 
            background-color: #ffffff;
            color: #fff; 
            position: fixed; 
            bottom: 0; 
            left: 0; 
            z-index: 1000; 
            padding: 10px 0; 
            display: flex; 
            justify-content: space-between;
            box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
            padding-left: 10px; 
            padding-right: 10px; 
        }
        .footer-buttons button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            text-align: center;
        }
        .footer-buttons button:hover {
            background-color: #0056b3;
        }
        .checkout-button {
            position: fixed;
            bottom: 100px;
            right: 20px;
            background-color: #007bff;
            border: none;
            color: white;
            padding: 20px 20px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 24px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        .modal {
            display: none; /* 隐藏模态框 */
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
        }
        .modal-content {
            background-color: #fff;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            border-radius: 8px;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 顶部 -->
        <div class="header">
            <img src="./images/cafeteria-logo.png" alt="Logo">
            <div class="user">
                <span id="userPhone">你好，<span id="userPhoneNumber"></span></span>
            </div>
        </div>

        <!-- 购物车商品列表 -->
        <div class="cart-items" id="cart-items">
            <!-- 购物车商品加载 -->
        </div>

        <div class="footer-buttons">
            <a href="consumer-dashboard.html">
                <button>菜单</button>
            </a>
            <a href="cart.html">
                <button>购物车</button>
            </a>
            <a href="rank.html">
                <button>排行榜</button>
            </a>
            <a href="my.html">
                <button>我的</button>
            </a>
        </div>
        
    </div>

    <!-- 结算按钮 -->
    <button class="checkout-button" onclick="openCheckoutModal()">结算</button>

    <!-- 结算模态框 -->
    <div id="checkoutModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeCheckoutModal()">&times;</span>
            <h3>结算</h3>
            <p>总金额: ¥<span id="totalAmount"></span></p>
            <!-- 移除餐桌编号输入框 -->
            <button onclick="submitOrder()">提交订单</button>
        </div>
    </div>

    <script>
        let userPhone = "未知"; // 默认值
        let totalAmount = 0;

        // 加载购物车商品
        function loadCartItems() {
            fetch('/api/cart')
                .then(response => response.json())
                .then(data => {
                    console.log(data);  // 打印返回的数据，检查是否正确
                    const cartItemsContainer = document.getElementById('cart-items');
                    cartItemsContainer.innerHTML = ''; // 清空现有的购物车商品
                    totalAmount = 0;

                    // 确保 data.cartItems 存在
                    if (data.cartItems && data.cartItems.length > 0) {
                        data.cartItems.forEach(item => {
                            totalAmount += item.product.price * item.quantity;
                            const cartItemDiv = document.createElement('div');
                            cartItemDiv.className = 'cart-item';
                            cartItemDiv.innerHTML = ` 
                                <img src="/images/products/${item.product.picture_path}" alt="${item.product.name}" />
                                <div class="cart-item-details">
                                    <h3>${item.product.name}</h3>
                                    <p>价格: ¥${item.product.price}</p>
                                    <p>数量: ${item.quantity}</p>
                                    <p>总价: ¥${(item.product.price * item.quantity).toFixed(2)}</p>
                                </div>
                                <div class="cart-item-actions">
                                    <button onclick="removeCartItem(${item.id})">删除</button>
                                </div>
                            `;
                            cartItemsContainer.appendChild(cartItemDiv);
                        });
                    } else {
                        cartItemsContainer.innerHTML = '<p>购物车为空</p>';
                    }
                })
                .catch(error => {
                    console.error('Failed to load cart items:', error);
                });
        }


        // 加载用户信息
        function loadUserInfo() {
            fetch('/api/user_info')
                .then(response => response.json())
                .then(data => {
                    userPhone = data.phone_number;
                    document.getElementById('userPhoneNumber').innerText = userPhone || '未知';
                }).catch(error => {
                    console.error('Failed to fetch user info:', error);
                    document.getElementById('userPhoneNumber').innerText = '未知';
                });
        }

        // 删除购物车商品
        function removeCartItem(cartItemId) {
            fetch(`/api/cart/${cartItemId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('商品已从购物车中删除');
                    loadCartItems(); // 重新加载购物车商品
                } else {
                    alert('删除失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败');
            });
        }

        // 打开结算模态框
        function openCheckoutModal() {
            document.getElementById('totalAmount').innerText = totalAmount.toFixed(2);
            document.getElementById('checkoutModal').style.display = 'block';
        }

        // 关闭结算模态框
        function closeCheckoutModal() {
            document.getElementById('checkoutModal').style.display = 'none';
        }

        // 提交订单
        function submitOrder() {
            // 不再需要地址字段，直接提交订单
            fetch('/api/checkout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({})
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('订单已提交');
                    // 这里可以跳转到订单确认页面或者清空购物车
                } else {
                    alert('提交订单失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('提交订单失败');
            });
        }

        document.addEventListener('DOMContentLoaded', function() {
            loadCartItems();
            loadUserInfo();
        });
    </script>
</body>
</html>
